
//HAL

//BSP
#include "lib/led.h"
//OS
#include "jxos_public.h"

static JXOS_EVENT_HANDLE key_press_event;
static swtime_type led_blink_swt;

static uint8_t led_msg_buff[sizeof(LED_MSG_STRUCT)*8];
static JXOS_MSG_HANDLE led_msg;

static LED_GROUP_STRUCT LEDS;
static LED_STRUCT led_space[LED_TASK_LED_NUM_MAX];

void (*std_app_led_task_hal_init_callback)(void) = 0;
void (*std_app_led_task_hal_led_on_callback)(uint8_t led_num) = 0;
void (*std_app_led_task_hal_led_off_callback)(uint8_t led_num) = 0;

static void led_task(uint8_t task_id, void * parameter)
{
	LED_MSG_STRUCT msg_item;
    if(jxos_msg_check_empty(led_msg) != 1){
        if(jxos_msg_receive(led_msg, &msg_item) == 1){
            if((msg_item.blink_times > 0)&&(msg_item.period > 0)&&(msg_item.on_time > 0)){
                led_blink_start(&(led_space[msg_item.led_num]),
                                    msg_item.period, msg_item.on_time, msg_item.blink_times);
            }
            else{
                led_blink_stop(&(led_space[msg_item.led_num]));
                if(msg_item.on_off == 0){
                    led_off(&(led_space[msg_item.led_num]));
                }
                else if(msg_item.on_off == 1){
                    led_on(&(led_space[msg_item.led_num]));
                }
                else if(msg_item.on_off == 2){
                    led_toggle(&(led_space[msg_item.led_num]));
                }
            }
        }
        else{
            jxos_msg_clean_up(led_msg);
        }
    }
	if(sys_svc_software_timer_check_overtime(led_blink_swt) == 1){
		led_group_tick_handler(&LEDS, LED_TASK_LED_BLINK_TICK_TIME);
	}
}

/******************************/
static uint8_t led_st_to_led_num(LED_STRUCT* led)
{
    uint8_t i;
    for(i = 0; i < LED_TASK_LED_NUM_MAX; i++){
        if(led == &(led_space[i])){
            break;
        }
    }
    if(i == LED_TASK_LED_NUM_MAX){
        i = 0xff;
    }
    return i;
}

static void led_on_handler(LED_STRUCT* led)
{
    uint8_t led_num = led_st_to_led_num(led);
    if(led_num != 0xff){
        std_app_led_task_hal_led_on_callback(led_num);
    }
}

static void led_off_handler(LED_STRUCT* led)
{
    uint8_t led_num = led_st_to_led_num(led);
    if(led_num != 0xff){
        std_app_led_task_hal_led_off_callback(led_num);
    }
}

/******************************/
void std_app_led_task_init(void)
{
    uint8_t i;

	//HAL
	if(std_app_led_task_hal_init_callback != 0){
		std_app_led_task_hal_init_callback();
	}

	//BSP
    led_group_init(&LEDS, LED_TASK_LED_NUM_MAX, led_space);
    for(i = 0; i < LED_TASK_LED_NUM_MAX; i++){
        led_new(&LEDS, led_on_handler, led_off_handler);
    }

	//OS
	jxos_task_create(led_task, "led", 0);
    led_msg = jxos_msg_create(led_msg_buff, 32, sizeof(LED_MSG_STRUCT), "std_app_led_msg");

	//LIB

	//SYS TASK
	led_blink_swt = sys_svc_software_timer_new();
	sys_svc_software_timer_set_time(led_blink_swt, LED_TASK_LED_BLINK_TICK_TIME);
	sys_svc_software_timer_restart(led_blink_swt);
}


